// 入口文件（模块）

import { ITodoData } from "./js/typings";
import TodoEvent from "./js/TodoEvent";


;((doc) => {
  // 先获取输入框、按钮、列表元素
  const oInput: HTMLInputElement = document.querySelector('input');
  const oAddBtn: HTMLButtonElement = document.querySelector('button');
  const oTodoList: HTMLElement = document.querySelector('.todo-list');

  const todoData: ITodoData[] = [
    {
      id: 1,
      content: '123',
      completed: false
    },
    {
      id: 2,
      content: '234',
      completed: true
    },
    {
      id: 3,
      content: '345',
      completed: false
    }
  ];

  const todoEvent: TodoEvent = new TodoEvent(todoData, oTodoList)

  // 一个模块需要启动 (没有返回值 都是给 void类型声明)
  const init = (): void => {
    bindEvent()
  };

  // 事件处理函数的绑定
  function bindEvent(): void {
    oAddBtn.addEventListener('click', handleAddBtnClick, false);
    oTodoList.addEventListener('click', handleListClick, false);
  };

  function handleAddBtnClick(): void {
    // 先获取input里面的值
    const val: string = oInput.value.trim();
    console.log('data长度:'+ todoData.length)
    const id: number = todoData.length + 1

    if (val.length) {
      const ret = todoEvent.addTodo(<ITodoData>{
        id: id,
        content: val,
        completed: false
      });
      
      if (ret && ret === 1001) {
        alert('列表项已存在');
        return;
      }

      oInput.value = ''
    }
  }

  function handleListClick(e: MouseEvent): void {
    //  as HTMLElement 如果不断言为 HTMLElement, tar.tagName找不到
    const tar = e.target as HTMLElement;
    const tagName = tar.tagName.toLowerCase(); // 因为得到的标签名是大写
    // console.log(tar)
    // console.log(tagName)

    if(tagName === 'input' || tagName === 'button') {
      const id = parseInt(tar.dataset.id)
      switch (tagName) {
        case 'input':
          todoEvent.toggleComplete(tar, id)
          break;
        case 'button':
          todoEvent.removeTodo(tar, id)
          break;
        default:
          break;
      }
    }
  }

  init();

})(document)